package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.ProUpdateHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.detailtab.pojo.ExpresssAddressPojo;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.InvoiceErrorCodeEnum;
import com.xbongbong.pro.invoice.pojo.InvoiceCommonSavePojo;
import com.xbongbong.pro.invoice.pojo.InvoiceRelationshipEditPojo;
import com.xbongbong.pro.invoice.pojo.RefTypePojo;
import com.xbongbong.pro.message.constant.InvoicePushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.entity.CustomerExpressEntity;
import com.xbongbong.saas.domain.entity.CustomerInvoiceEntity;
import com.xbongbong.saas.domain.entity.InvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.RefundInvoiceEntity;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.enums.CustomerExpressEnum;
import com.xbongbong.saas.enums.CustomerInvoiceEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.RefTypeEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.model.CustomerExpressModel;
import com.xbongbong.saas.model.CustomerInvoiceModel;
import com.xbongbong.saas.model.InvoiceRelationshipModel;
import com.xbongbong.saas.model.RefundInvoiceModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
@Slf4j
public class InvoiceHelp {

    @Resource
    private CustomerInvoiceModel customerInvoiceModel;
    @Resource
    private CustomerExpressModel customerExpressModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private InvoiceRelationshipModel invoiceRelationshipModel;
    @Resource
    private ProUpdateHelp proUpdateHelp;
    @Resource
    private RefundInvoiceModel refundInvoiceModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private MessageService messageService;

    /**
     * Description: 从 com.xbongbong.saas.help.InvoiceCommonHelper#saveCustomerInvoiceAndExpress(java.lang.String, java.lang.Long, java.lang.String, java.lang.String, com.alibaba.fastjson.JSONArray, com.alibaba.fastjson.JSONArray) 溢出
     * @param corpid
	 * @param customerId
	 * @param creatorId
	 * @param loginUserName
	 * @param customerInvoice
	 * @param customerExpress
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/8/19 13:53
     * @since
     */
    public void saveCustomerInvoiceAndExpress(String corpid, Long customerId, String creatorId, String loginUserName, JSONArray customerInvoice, JSONArray customerExpress) throws XbbException {
        if(CollectionsUtil.isNotEmpty(customerInvoice)) {
            CustomerInvoiceEntity customerInvoiceEntity = new CustomerInvoiceEntity();
            JSONObject customerInvoiceObject = customerInvoice.getJSONObject(0);
            String titleType = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject, CustomerInvoiceEnum.TITLE_TYPE.getAttr(),"");
            String title = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject,CustomerInvoiceEnum.TITLE.getAttr(),"");
            String taxpayerNo = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject,CustomerInvoiceEnum.TAXPAYER_NO.getAttr(),"");
            String registeredPhone = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject,CustomerInvoiceEnum.REGISTERED_PHONE.getAttr(),"");
            String invoiceAddress = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject,CustomerInvoiceEnum.INVOICE_ADDRESS.getAttr(),"");
            String bank = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject,CustomerInvoiceEnum.BANK.getAttr(),"");
            String account = FastJsonHelper.getStringOrDefaultFromFormData(customerInvoiceObject,CustomerInvoiceEnum.ACCOUNT.getAttr(),"");
            if(Objects.equals(titleType,"") && Objects.equals(title,"") && Objects.equals(taxpayerNo,"") && Objects.equals(registeredPhone,"") && Objects.equals(invoiceAddress,"") && Objects.equals(bank,"") && Objects.equals(account,"")){
                return;
            }
            customerInvoiceEntity.setTitleType(titleType);
            customerInvoiceEntity.setTitle(title);
            customerInvoiceEntity.setTaxpayerNo(taxpayerNo);
            customerInvoiceEntity.setRegisteredPhone(registeredPhone);
            customerInvoiceEntity.setInvoiceAddress(invoiceAddress);
            customerInvoiceEntity.setBank(bank);
            customerInvoiceEntity.setAccount(account);
            customerInvoiceEntity.setCorpid(corpid);
            customerInvoiceEntity.setCustomerId(customerId);
            customerInvoiceEntity.setCreatorId(creatorId);
            customerInvoiceEntity.setCreatorName(loginUserName);
            customerInvoiceEntity.setModifierId(creatorId);
            customerInvoiceEntity.setModifierName(loginUserName);
            customerInvoiceEntity.setDel(DelEnum.NORMAL.getDel());
            customerInvoiceEntity.setIsDefault(BasicConstant.ONE);
            try {
                customerInvoiceModel.insert(customerInvoiceEntity);
            } catch (Exception e) {
                throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
            }
        }

        if(CollectionsUtil.isNotEmpty(customerExpress)){
            CustomerExpressEntity customerExpressEntity = new CustomerExpressEntity();
            JSONObject customerExpressObject = customerExpress.getJSONObject(0);
            String name = FastJsonHelper.getStringOrDefaultFromFormData(customerExpressObject, CustomerExpressEnum.NAME.getAttr(),"");
            String contact = FastJsonHelper.getStringOrDefaultFromFormData(customerExpressObject,CustomerExpressEnum.CONTACT.getAttr(),"");
            String phone = FastJsonHelper.getStringOrDefaultFromFormData(customerExpressObject,CustomerExpressEnum.PHONE.getAttr(),"");
            String zipCode = FastJsonHelper.getStringOrDefaultFromFormData(customerExpressObject,CustomerExpressEnum.ZIP_CODE.getAttr(),"");
            String addressJson = FastJsonHelper.getStringOrDefaultFromFormData(customerExpressObject,CustomerExpressEnum.ADDRESS.getAttr(),"");
            String province = "";
            String city = "";
            String district = "";
            String address = "";
            if(Objects.nonNull(addressJson) && !Objects.equals(addressJson,"")){
                ExpresssAddressPojo addressPojo = JSONObject.parseObject(addressJson,ExpresssAddressPojo.class);
                province = addressPojo.getProvince();
                city = addressPojo.getCity();
                district = addressPojo.getDistrict();
                address = addressPojo.getAddress();
            }
            if(Objects.equals(name,"") && Objects.equals(contact,"") && Objects.equals(phone,"") && Objects.equals(zipCode,"") && Objects.equals(province,"") && Objects.equals(city,"") && Objects.equals(district,"") && Objects.equals(address,"")){
                return;
            }
            customerExpressEntity.setCreatorId(creatorId);
            customerExpressEntity.setCreatorName(loginUserName);
            customerExpressEntity.setCorpid(corpid);
            customerExpressEntity.setCustomerId(customerId);
            customerExpressEntity.setName(name);
            customerExpressEntity.setContact(contact);
            customerExpressEntity.setPhone(phone);
            customerExpressEntity.setZipCode(zipCode);
            customerExpressEntity.setProvince(province);
            customerExpressEntity.setCity(city);
            customerExpressEntity.setDistrict(district);
            customerExpressEntity.setAddress(address);
            customerExpressEntity.setIsDefault(BasicConstant.ONE);
            customerExpressEntity.setModifierId(creatorId);
            customerExpressEntity.setModifierName(loginUserName);
            customerExpressEntity.setDel(BasicConstant.ZERO);
            try {
                customerExpressModel.save(customerExpressEntity);
            } catch (Exception e){
                throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
            }
        }
    }


    /**
     * 建立发票关系
     *
     * @param isEnable     是否审批
     * @param invoiceId    发票id
     * @param now          时间
     * @param customerId   客户id
     * @param customerName 客户名称
     * @param corpid       公司id
     * @param money        金额
     * @param contractId   合同id
     * @param contractNo   合同编号
     * @param paymentId    回款id
     * @param paymentNo    回款编号
     * @param type         类性
     * @throws XbbException 异常
     */
    public InvoiceRelationshipEntity buildNewInvoiceRelation(boolean isEnable, Long invoiceId, Long now, Long customerId, String customerName, String corpid, Double money, Long contractId, String contractNo, Long paymentId, String paymentNo, Long paymentSheetId, String paymentSheetNo, Integer type) throws XbbException {
        InvoiceRelationshipEntity invoiceRelationshipEntity = new InvoiceRelationshipEntity();
        invoiceRelationshipEntity.setInvoiceId(invoiceId);
        invoiceRelationshipEntity.setAddTime(now);
        invoiceRelationshipEntity.setUpdateTime(now);
        invoiceRelationshipEntity.setCustomerId(customerId);
        invoiceRelationshipEntity.setCustomerName(customerName);
        invoiceRelationshipEntity.setCorpid(corpid);
        invoiceRelationshipEntity.setIsCancel(BasicConstant.ZERO);
        invoiceRelationshipEntity.setDel(DelEnum.NORMAL.getDel());
        invoiceRelationshipEntity.setMoney(money);
        invoiceRelationshipEntity.setContractId(contractId);
        invoiceRelationshipEntity.setContractNo(contractNo);
        invoiceRelationshipEntity.setContractName("");
        invoiceRelationshipEntity.setPaymentId(paymentId);
        invoiceRelationshipEntity.setPaymentNo(paymentNo);
        invoiceRelationshipEntity.setPaymentSheetId(paymentSheetId);
        invoiceRelationshipEntity.setPaymentSheetNo(paymentSheetNo);
        if (isEnable) {
            invoiceRelationshipEntity.setFlowStatus(FlowStatusEnum.APPROVAL_PENDING.getType());
        } else {
            invoiceRelationshipEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
        }
        invoiceRelationshipEntity.setType(type);
        return invoiceRelationshipEntity;
    }


    public void invoiceMessagePushHandle(InvoiceCommonSavePojo invoiceCommonSavePojo) throws XbbException{
        PaasFormDataEntity newPaasFormDataEntity = invoiceCommonSavePojo.getEntityExt();
        String creatorId = newPaasFormDataEntity.getCreatorId();
        String corpid = invoiceCommonSavePojo.getCorpid();
        boolean isNew = invoiceCommonSavePojo.getIsNew();
        Long originId = invoiceCommonSavePojo.getOriginId();
        Long invoiceId = invoiceCommonSavePojo.getInvoiceId();
        Integer isImport = invoiceCommonSavePojo.getIsImport();
        Integer businessType = invoiceCommonSavePojo.getBusinessType();
        Integer subBusinessType = invoiceCommonSavePojo.getSubBusinessType();
        UserEntity creatorUser = userModel.getByKeyIngoreDel(creatorId, corpid);
        if(isNew) {
            if (originId > BasicConstant.ZERO) {
                if (!Objects.equals(isImport, 1)) {
                    // 红冲发票创建消息推送
                    InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                    BeanUtil.copyProperties(newPaasFormDataEntity, invoiceEntityExt);
                    List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.INVOICE_RED_ADD_PUSH.getCode(), PushTypeEnum.INVOICE_RED_ADD_PUSH.getSubCode(), invoiceCommonSavePojo.getLoginUser(), invoiceEntityExt);
                    PushRefTypePojo.Options options = new PushRefTypePojo.Options(invoiceEntityExt.getAppId(), invoiceEntityExt.getMenuId(), invoiceEntityExt.getFormId(), invoiceId, Collections.singletonList(invoiceId), SaasMarkEnum.SAAS.getCode(), businessType, subBusinessType);
                    MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(invoiceId), 0, null, I18nMessageUtil.getMessage(InvoicePushConstant.INVOICE_RED_ADD_TITLE), String.format(I18nMessageUtil.getMessage(InvoicePushConstant.INVOICE_RED_ADD_CONTENT), creatorUser.getName(), invoiceEntityExt.getSerialNo()), null, options);
                    messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.INVOICE_RED_ADD_PUSH);
                }
            } else {
                if (!Objects.equals(isImport, 1)) {
                    // 发票创建消息推送
                    InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                    BeanUtil.copyProperties(newPaasFormDataEntity, invoiceEntityExt);
                    List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.INVOICE_ADD_PUSH.getCode(), PushTypeEnum.INVOICE_ADD_PUSH.getSubCode(), invoiceCommonSavePojo.getLoginUser(), invoiceEntityExt);
                    PushRefTypePojo.Options options = new PushRefTypePojo.Options(invoiceEntityExt.getAppId(), invoiceEntityExt.getMenuId(), invoiceEntityExt.getFormId(), invoiceId, Collections.singletonList(invoiceId), SaasMarkEnum.SAAS.getCode(), businessType, subBusinessType);
                    MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(invoiceId), 0, null,I18nMessageUtil.getMessage(InvoicePushConstant.INVOICE_ADD_TITLE), String.format(I18nMessageUtil.getMessage(InvoicePushConstant.INVOICE_ADD_CONTENT), creatorUser.getName(), newPaasFormDataEntity.getSerialNo()), null, options);
                    messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.INVOICE_ADD_PUSH);
                }
            }
        }
    }

    /**
     * 发票编辑时新增删除数据
     *  老的数据减去新的数据得到删除的关联数据,新的减去老的得到新增的关联数据
     * @param newData
     * @param oldData
     * @param corpid
     * @param invoiceId
     * @return
     * @throws XbbException
     */
    public InvoiceRelationshipEditPojo getAddOrDeleteRelationship(JSONObject newData, JSONObject oldData, String corpid, Long invoiceId)throws XbbException{
        // 老的
        List<Long> oldPaymentIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, InvoiceEnum.PAYMENT_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
        List<Long> oldContractIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, InvoiceEnum.CONTRACT_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
        //回款单的
        List<Long> oldPaymentSheetIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData,InvoiceEnum.PAYMENT_SHEET_ID.getAttr(),new JSONArray()).toJavaList(Long.class);
        // 新的
        List<Long> paymentIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(newData, InvoiceEnum.PAYMENT_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
        List<Long> contractIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(newData, InvoiceEnum.CONTRACT_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
        //回款单的
        List<Long> paymentSheetIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(newData, InvoiceEnum.PAYMENT_SHEET_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
        oldPaymentIdList.removeAll(paymentIdList);
        oldContractIdList.removeAll(contractIdList);
        oldPaymentSheetIdList.removeAll(paymentSheetIdList);
        //删掉减去的，并更新到对应的关联数据里
        invoiceEditAmountCompute(corpid,invoiceId,oldPaymentIdList, RefTypeEnum.PAYMENT);
        invoiceEditAmountCompute(corpid,invoiceId,oldContractIdList,RefTypeEnum.CONTRACT);
        invoiceEditAmountCompute(corpid,invoiceId,oldPaymentSheetIdList,RefTypeEnum.PAYMENTSHEET);
        return new InvoiceRelationshipEditPojo(oldPaymentIdList,oldContractIdList,oldPaymentSheetIdList,paymentIdList,contractIdList,paymentSheetIdList);
    }


    /**
     * 发票编辑的时候老发票如果被删除可以先进行累加在从发票金额上减去
     * @param corpid 公司编号
     * @param invoiceId 发票id
     * @param idList 关联id 集合
     * @param refTypeEnum 关联的枚举类型
     * @throws XbbException
     */
    private void invoiceEditAmountCompute(String corpid,Long invoiceId,List<Long> idList,RefTypeEnum refTypeEnum) throws XbbException{
        if(CollectionsUtil.isEmpty(idList)){
            return;
        }
        RefTypePojo refTypePojo = getRefType(refTypeEnum);
        InvoiceEnum invoiceEnum = refTypePojo.getInvoiceEnum();
        Integer businessType = refTypePojo.getBusinessType();
        String attr = refTypePojo.getInvoiceAmountAttr();
        Map<Long, PaasFormDataEntityExt> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //获取除去减去的关联id对应关联实体的 map
        Map<Long, List<InvoiceRelationshipEntity>> oldInvoiceMap = getInvoiceMap(corpid, invoiceId, idList, invoiceEnum);
        if(Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())){
            List<PaasFormDataEntityExt> contractList = paasEsModel.getByIdList(idList, corpid, SaasMarkEnum.SAAS.getCode(), businessType, new ArrayList<>(), IndexTypeEnum.IDX_SAAS_CONTRACT);
            contractList.forEach(contract-> contractMap.put(contract.getId(), contract));
        }
        for (Long id : idList) {
            List<InvoiceRelationshipEntity>  singleRelationInvoiceList = oldInvoiceMap.get(id);
            Double otherInvoiceSumAmount = 0D;
            if (CollectionsUtil.isNotEmpty(singleRelationInvoiceList)) {
                for (InvoiceRelationshipEntity invoiceRelationshipEntity : singleRelationInvoiceList) {
                    otherInvoiceSumAmount = Arith.add(otherInvoiceSumAmount,invoiceRelationshipEntity.getMoney());
                }
            }
            if(Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode())) {
                if (Objects.nonNull(contractMap.get(id))) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(ContractEnum.INVOICE_AMOUNT.getAttr(), otherInvoiceSumAmount);
                    Double amount = contractMap.get(id).getData().getDouble(ContractEnum.AMOUNT.getAttr());
                    jsonObject.put(ContractEnum.UN_INVOICE_AMOUNT.getAttr(), amount - otherInvoiceSumAmount);
                    proUpdateHelp.update(businessType, corpid, id, jsonObject);
                }
            }else {
                proUpdateHelp.update(businessType, corpid, id, attr, otherInvoiceSumAmount);
            }
        }
    }

    /**
     * 获取发票的关联类型pojo
     * @param refTypeEnum
     * @return
     * @throws XbbException
     */
    private RefTypePojo getRefType(RefTypeEnum refTypeEnum) throws XbbException{
        RefTypePojo refTypePojo = new RefTypePojo();
        switch (refTypeEnum){
            case CONTRACT:
                refTypePojo.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
                refTypePojo.setInvoiceEnum(InvoiceEnum.CONTRACT_ID);
                refTypePojo.setAmountAttr(ContractEnum.AMOUNT.getAttr());
                refTypePojo.setInvoiceAmountAttr(ContractEnum.INVOICE_AMOUNT.getAttr());
                break;
            case PAYMENT:
                refTypePojo.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                refTypePojo.setInvoiceEnum(InvoiceEnum.PAYMENT_ID);
                refTypePojo.setAmountAttr(PaymentEnum.AMOUNT.getAttr());
                refTypePojo.setInvoiceAmountAttr(PaymentEnum.INVOICE_AMOUNT.getAttr());
                break;
            case PAYMENTSHEET:
                refTypePojo.setBusinessType(XbbRefTypeEnum.PAYMENT_SHEET.getCode());
                refTypePojo.setInvoiceEnum(InvoiceEnum.PAYMENT_SHEET_ID);
                refTypePojo.setAmountAttr(PaymentSheetEnum.AMOUNT.getAttr());
                refTypePojo.setInvoiceAmountAttr(PaymentSheetEnum.INVOICE_AMOUNT.getAttr());
                break;
            default:
                throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_216021);
        }
        return refTypePojo;
    }

    /**
     * 根据合同id/应收款id/回款单id 放入一个map 对应的值为开票的关联实体
     * @param corpid
     * @param invoiceId
     * @param oldRelationIdList
     * @param invoiceEnum
     * @return
     * @throws XbbException
     */
    private Map<Long, List<InvoiceRelationshipEntity>> getInvoiceMap(String corpid, Long invoiceId, List<Long> oldRelationIdList, InvoiceEnum invoiceEnum) throws XbbException {
        Map<Long, List<InvoiceRelationshipEntity>> oldInvoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<InvoiceRelationshipEntity> relationList = getRelationShipInvoice(invoiceId, corpid, oldRelationIdList, invoiceEnum);
        relationList.forEach(relation -> {
            Long relationId = 0L;
            if (Objects.equals(invoiceEnum, InvoiceEnum.PAYMENT_ID)) {
                relationId = relation.getPaymentId();
            } else if (Objects.equals(invoiceEnum, InvoiceEnum.CONTRACT_ID)) {
                relationId = relation.getContractId();
            }else if(Objects.equals(invoiceEnum,InvoiceEnum.PAYMENT_SHEET_ID)){
                relationId = relation.getPaymentSheetId();
            }
            List<InvoiceRelationshipEntity> list = new ArrayList<>();
            if (oldInvoiceMap.containsKey(relationId)) {
                list = oldInvoiceMap.get(relationId);
            }
            list.add(relation);
            oldInvoiceMap.put(relationId, list);
        });
        return oldInvoiceMap;
    }


    public List<InvoiceRelationshipEntity> getRelationShipInvoice(Long invoiceId, String corpid, List<Long> relationIdList, InvoiceEnum invoiceEnum) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.IS_CANCEL, 0);
        param.put("invoiceIdnot", invoiceId);
        if (Objects.equals(invoiceEnum, InvoiceEnum.CONTRACT_ID)) {
            param.put("contractIdIn", relationIdList);
        } else if (Objects.equals(invoiceEnum, InvoiceEnum.PAYMENT_ID)) {
            param.put("paymentIdIn", relationIdList);
        } else if(Objects.equals(invoiceEnum, InvoiceEnum.PAYMENT_SHEET_ID)){
            param.put("paymentSheetIdIn",relationIdList);
        }
        return invoiceRelationshipModel.findEntitys(param);
    }


    /**
     * Description: 更新退货退款中的发票ID
     * @param refundId
	 * @param invoiceId
	 * @param invoiceData
	 * @param corpid
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/8/19 17:27
     * @since
     */
    public void updateRefundInvoiceId(Long refundId, Long invoiceId, JSONObject invoiceData, String corpid) throws XbbException {
        RefundEntityExt refundEntityExt = refundModel.getByKey(refundId, corpid);
        JSONObject newData = new JSONObject();
        JSONObject oldData = refundEntityExt.getData();
        JSONArray invoiceIds = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, RefundEnum.INVOICES.getAttr(), new JSONArray());
        invoiceIds.add(invoiceId);
        newData.put(RefundEnum.INVOICES.getAttr(), invoiceIds);
        JSONArray paymentSheetNames = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, RefundEnum.INVOICES_LINKED_TEXT.getAttr(), new JSONArray());
        paymentSheetNames.add(invoiceData.getString(FieldTypeEnum.SERIALNO.getAlias()));
        newData.put(RefundEnum.INVOICES_LINKED_TEXT.getAttr(), paymentSheetNames);
        proUpdateHelp.update(XbbRefTypeEnum.REFUND.getCode(), corpid, refundId, newData);

        Long now = DateTimeUtil.getInt();
        RefundInvoiceEntity refundInvoiceEntity = new RefundInvoiceEntity();
        refundInvoiceEntity.setRefundId(refundId);
        refundInvoiceEntity.setCorpid(corpid);
        refundInvoiceEntity.setDel(DelEnum.NORMAL.getDel());
        refundInvoiceEntity.setAddTime(now);
        refundInvoiceEntity.setUpdateTime(now);
        refundInvoiceEntity.setInvoiceId(invoiceId);
        refundInvoiceEntity.setRedContractId(0L);
        refundInvoiceEntity.setRedPaymentId(0L);
        refundInvoiceEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
        refundInvoiceModel.save(refundInvoiceEntity);
    }
}
